from flask import Blueprint,render_template,request,jsonify,session
from utils import db
from . import input_info

us = Blueprint('user', __name__)

# 添加用户信息接口
@us.route('/user',methods=['POST'])
def add_user():
    data = input_info.input_user_info()
    if data:
        hash_password = db.hash_password(data['password'])
        result = input_info.norm_user_info()
        if 'success' in result and result['success'] == True:
            # 在添加用户之前进行数据库备份
            backup_result = db.backup_database()
            if '成功' not in backup_result:
                return render_template('user_list.html', error=f'数据库备份失败: {backup_result}')
            
            add_user_sql = "INSERT INTO user(remark,telephone1,telephone2,role,account,password) VALUES(%s,%s,%s,1,%s,%s)"
            db.execute(add_user_sql, [data['remark'],data['telephone1'],data['telephone2'],data['account'],hash_password])
            return render_template('user_list.html',success='添加成功')
        else:
            return render_template('user_list.html',error=result['msg'])
    else:
        return render_template('user_list.html',error='未输入信息！')

# 展示用户原信息接口
@us.route("/user/<ID>/update", methods=['GET'])
def show_user_info(ID):
    user = db.get_one("select * from user WHERE ID = %s", [ID])
    if user:
        return jsonify({
            'remark': user['remark'],
            'telephone1': user['telephone1'],
            'telephone2': user['telephone2'],
        })
    else:
        return jsonify({'error': '用户不存在'}), 404

# 修改用户信息接口
@us.route('/user/<ID>/update',methods=['PUT'])
def update_user(ID):
    user_info = session.get("user_info")
    if user_info['role'] == 2:
        # 在修改用户信息之前进行数据库备份
        backup_result = db.backup_database()
        if '成功' not in backup_result:
            return jsonify({'success': False, 'message': f'数据库备份失败: {backup_result}'})
        
        remark = request.json.get('remark')
        telephone1 = request.json.get('telephone1')
        telephone2 = request.json.get('telephone2')
        update_user_sql = "update user set remark=%s,telephone1=%s,telephone2=%s where ID=%s"
        db.execute(update_user_sql, [remark,telephone1,telephone2,ID])
        return jsonify({'success': True, 'message': '修改成功'})
    else:
        return jsonify({'success': False, 'message': '没有权限进行此操作'})

# 修改用户密码接口
@us.route('/user/<ID>/password',methods=['PUT'])
def update_password(ID):
    old_password = request.json.get('oldPassword')
    user = db.get_one("select password from user where ID=%s",[ID])
    if db.verify_password(old_password,user['password'])==True:
        new_password = request.json.get('newPassword')
        if not new_password:
            return jsonify({'success': False, 'message':'未输入新密码！'})
        else:
            hash_new_password = db.hash_password(new_password)
            update_user_sql = "update user set password=%s where ID=%s"
            db.execute(update_user_sql,[hash_new_password,ID])
            return jsonify({'success': True,'message':'修改成功','redirectTo':'/logout'})
    else:
        return jsonify({'success': False, 'message':'原密码错误！'})


# 删除用户信息接口
@us.route('/user/<ID>',methods=['DELETE'])
def delete_user(ID):
    delete_user_sql = "DELETE FROM user WHERE ID=%s"
    db.execute(delete_user_sql,[ID])
    return render_template('user_list.html',success='删除成功')


